import { useState, useEffect } from 'react'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { View, Text, Image, ScrollView } from '@tarojs/components'
import { Empty, Button, Loading } from '@taroify/core'
import { ArrowLeft, Replay, StarOutlined } from '@taroify/icons'
import recipeService from '../utils/recipeService'
import './generate.scss'

const Generate = () => {
  const [recipes, setRecipes] = useState([])
  const [mode, setMode] = useState('random') // 'random' 或 'ingredients'
  const [selectedIngredients, setSelectedIngredients] = useState([])
  const [loading, setLoading] = useState(true)
  const [recipeData, setRecipeData] = useState([])
  const [error, setError] = useState(null)
  const [isShaking, setIsShaking] = useState(false)
  const [shakeTip, setShakeTip] = useState('摇一摇手机，随机推荐一道菜')

  // 获取食谱数据和页面参数
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 从云端获取食谱数据
        const data = await recipeService.getRecipes()
        setRecipeData(data)

        // 处理页面参数
        const params = getCurrentInstance().router.params
        const currentMode = params.mode || 'random'
        setMode(currentMode)

        // 如果是按食材选择模式，解析食材列表
        if (currentMode === 'ingredients' && params.ingredients) {
          try {
            const ingredientsArray = JSON.parse(decodeURIComponent(params.ingredients))
            setSelectedIngredients(ingredientsArray)
            generateByIngredients(ingredientsArray, data)
          } catch (err) {
            console.error('解析食材参数出错:', err)
            setError('解析食材参数出错')
            setLoading(false)
          }
        } else {
          // 随机模式
          generateRandomRecipe(data)
          // // 随机模式初始状态，不自动生成，等待用户摇一摇或点击按钮
          // setLoading(false)
        }
      } catch (err) {
        console.error('获取食谱数据失败:', err)
        setError('加载失败，请重试')
        setLoading(false)
      }
    }

    fetchData()

    // 如果是随机模式，添加摇一摇事件监听
    // if (mode === 'random') {
    //   // initShakeEvent()
    //   setIsShaking
    //   generateRandomRecipe()
    //   setIsShaking(false)
    // }

    // 组件卸载时移除事件监听
    return () => {
      if (mode === 'random') {
        Taro.stopAccelerometer()
      }
    }
  }, [])

  // 初始化摇一摇事件
  // const initShakeEvent = () => {
  //   // 上一次摇动时间
  //   let lastTime = 0
  //   // 上一次摇动加速度
  //   let lastX = 0, lastY = 0, lastZ = 0
  //   // 摇动阈值
  //   const shakeThreshold = 200

  //   // 开始监听加速度数据
  //   Taro.startAccelerometer({ interval: 'ui' })

  //   // 监听加速度数据变化
  //   Taro.onAccelerometerChange((res) => {
  //     // 如果正在加载中，不处理摇动
  //     if (loading || isShaking) return

  //     const curTime = new Date().getTime()
  //     // 两次摇动间隔至少1秒
  //     if ((curTime - lastTime) < 1000) return

  //     const { x, y, z } = res
  //     const deltaX = Math.abs(x - lastX)
  //     const deltaY = Math.abs(y - lastY)
  //     const deltaZ = Math.abs(z - lastZ)

  //     // 判断是否达到摇动阈值
  //     if ((deltaX + deltaY + deltaZ) * 100 > shakeThreshold) {
  //       setIsShaking(true)
  //       setShakeTip('正在努力选菜...')
  //       lastTime = curTime

  //       // 播放振动反馈
  //       Taro.vibrateShort({ type: 'medium' })

  //       // 延迟一下再生成，给用户一个反馈过程
  //       setTimeout(() => {
  //         generateRandomRecipe()
  //         setIsShaking(false)
  //         setShakeTip('再次摇一摇，换一道菜')
  //       }, 800)
  //     }

  //     lastX = x
  //     lastY = y
  //     lastZ = z
  //   })
  // }

  // 根据食材生成推荐菜谱
  const generateByIngredients = (ingredients, data) => {
    setLoading(true)

    // 使用传入的数据或当前状态中的数据
    const recipeList = data || recipeData

    // 模拟加载过程
    setTimeout(() => {
      // 筛选出包含选中食材的菜谱
      const matchedRecipes = recipeList.filter((recipe) => {
        // 计算菜谱食材与选中食材的交集数量
        const matchCount = recipe.ingredients.filter((item) => ingredients.includes(item)).length

        // 如果至少有一种食材匹配，则保留该菜谱
        return matchCount > 0
      })

      // 根据匹配数量排序（匹配越多的排在前面）
      matchedRecipes.sort((a, b) => {
        const matchCountA = a.ingredients.filter((item) => ingredients.includes(item)).length
        const matchCountB = b.ingredients.filter((item) => ingredients.includes(item)).length
        return matchCountB - matchCountA
      })

      setRecipes(matchedRecipes)
      setLoading(false)
    }, 800) // 模拟延迟
  }

  // 生成随机菜谱
  const generateRandomRecipe = (data) => {
    setLoading(true)

    // 使用传入的数据或当前状态中的数据
    const recipeList = data || recipeData

    // 模拟加载过程
    setTimeout(() => {
      if (recipeList.length) {
        // 随机选择一道菜谱
        const randomIndex = Math.floor(Math.random() * recipeList.length)
        const randomRecipe = recipeList[randomIndex]
        setRecipes([randomRecipe])
      } else {
        setRecipes([])
      }
      setLoading(false)
    }, 800) // 模拟延迟
  }

  // 重新随机
  const refreshRandomRecipe = () => {
    if (mode === 'random') {
      generateRandomRecipe()
    } else {
      generateByIngredients(selectedIngredients)
    }
  }

  // 查看菜谱详情
  const viewRecipeDetail = (id) => {
    Taro.navigateTo({
      url: `/pages-recipe/detail?id=${id}`
    })
  }

  // 返回上一页
  const goBack = () => {
    // 获取页面栈
    const pages = Taro.getCurrentPages()
    // 如果只有一个页面（说明是从分享直接进入的首页）
    if (pages.length <= 1) {
      // 跳转到菜谱首页而不是使用navigateBack
      Taro.redirectTo({
        url: '/pages-recipe/index'
      })
    } else {
      Taro.navigateBack()
    }
  }

  // 渲染页面标题
  const renderTitle = () => {
    if (mode === 'random') {
      return '随机推荐'
    } else {
      return '为你推荐'
    }
  }

  // 渲染食材匹配度
  const renderMatchRate = (recipe) => {
    if (mode !== 'ingredients' || !selectedIngredients.length) return null

    const matchCount = recipe.ingredients.filter((item) => selectedIngredients.includes(item)).length

    const totalCount = recipe.ingredients.length
    const percentage = Math.round((matchCount / totalCount) * 100)

    return (
      <View className='match-rate'>
        <Text className='rate-label'>食材匹配度:</Text>
        <Text className='rate-value'>{percentage}%</Text>
      </View>
    )
  }

  return (
    <View className='generate-page'>
      <View className='header'>
        <View className='back-btn' onClick={goBack}>
          <ArrowLeft size='20' />
        </View>
        <Text className='title'>{renderTitle()}</Text>
        <View className='refresh-btn' onClick={refreshRandomRecipe}>
          <Replay size='20' />
        </View>
      </View>

      {/* 错误状态 */}
      {error && (
        <View className='error-container'>
          <Text className='error-text'>{error}</Text>
          <Button
            className='retry-btn'
            color='primary'
            size='small'
            onClick={() => {
              setError(null)
              setLoading(true)
              recipeService
                .getRecipes()
                .then((data) => {
                  setRecipeData(data)
                  if (mode === 'random') {
                    generateRandomRecipe(data)
                  } else {
                    generateByIngredients(selectedIngredients, data)
                  }
                })
                .catch((err) => {
                  console.error('重试失败:', err)
                  setError('重试加载失败，请稍后再试')
                  setLoading(false)
                })
            }}>
            重试
          </Button>
        </View>
      )}

      {/* 加载状态 */}
      {loading && !error && (
        <View className='loading-container'>
          <Loading type='spinner' color='#ff6b6b' />
          <Text className='loading-text'>正在为你挑选菜谱...</Text>
        </View>
      )}

      {/* 随机模式 - 摇一摇提示 */}
      {mode === 'random' && !loading && !error && recipes.length === 0 && (
        <View className='shake-container'>
          <View className='shake-icon'>
            <Image
              src='https://636c-cloud1-1ghcuz1u4c694d57-1304750880.tcb.qcloud.la/icons/shake.png'
              mode='aspectFit'
              className={isShaking ? 'shaking' : ''}
            />
          </View>
          <Text className='shake-tip'>{shakeTip}</Text>
          <Button
            className='generate-btn'
            color='primary'
            onClick={refreshRandomRecipe}
            disabled={loading || isShaking}
          >
            点击生成随机菜谱
          </Button>
        </View>
      )}

      {/* 没有找到匹配的菜谱 */}
      {!loading && !error && recipes.length === 0 && mode !== 'random' && (
        <View className='empty-container'>
          <Empty>
            <Empty.Image />
            <Empty.Description>
              没有找到匹配的菜谱
              {mode === 'ingredients' && '，试试减少食材条件吧'}
            </Empty.Description>
            <Button className='retry-btn' color='primary' size='small' onClick={goBack}>
              返回重选
            </Button>
          </Empty>
        </View>
      )}

      {/* 展示菜谱列表 */}
      {!loading && !error && recipes.length > 0 && (
        <ScrollView scrollY className='recipes-container'>
          {recipes.map((recipe) => (
            <View key={recipe.id} className='recipe-card' onClick={() => viewRecipeDetail(recipe.id)}>
              <Image className='recipe-image' src={recipe.image} mode='aspectFill' />
              <View className='recipe-content'>
                <Text className='recipe-name'>{recipe.name}</Text>

                {/* 匹配度（仅在食材选择模式下显示） */}
                {renderMatchRate(recipe)}

                <View className='recipe-tags'>
                  {recipe.tags.map((tag, index) => (
                    <Text key={index} className='tag'>
                      {tag}
                    </Text>
                  ))}
                  {recipe.isVegetarian && <Text className='tag vegetarian'>素食</Text>}
                </View>

                <View className='recipe-ingredients'>
                  <Text className='ingredients-label'>主要食材:</Text>
                  <Text className='ingredients-list'>
                    {recipe.ingredients.slice(0, 5).join('、')}
                    {recipe.ingredients.length > 5 ? '...' : ''}
                  </Text>
                </View>

                <View className='recipe-action'>
                  <Button className='view-btn' color='primary' size='small' icon={<StarOutlined />}>
                    查看详情
                  </Button>
                </View>
              </View>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  )
}

export default Generate
